#coding=utf-8
'''
Created on 2013年9月2日

@author: xuben
'''

import cn.common.ConfigManager as ConfigManager
import cn.common.GameConfig as GameConfig
import cn.common.HeartBeat as HeartBeat
import cn.common.Logger as Logger
import cn.common.PushCommand as PushCommand
import cn.common.SocketService as SocketService
import cn.common.ThreadManager as ThreadManager
import cn.general.General as General
import cn.general.GeneralData as GeneralData
import cn.general.GeneralManager as GeneralManager
import cn.login.LoginManager as LoginManager
import cn.maincity.MaincityManager as MaincityManager
import cn.resource.ResourceData as ResourceData
import cn.resource.ResourceManager as ResourceManager
import cn.role.Role as Role
import cn.war.WarData as WarData
import cn.war.WarManager as WarManager
import cn.world.World as World
import sys
import threading
import time
import traceback

'''
初始化环境
'''
def initContext():
    #把utf-8编码的str转成unicode时（系统自动转换，比如用+号连接）
    #如果没有明确指出编码方式，则会采用sys.defaultencoding，而这个值通常情况下是ascii
    if sys.getdefaultencoding != 'utf-8':
        reload(sys) # Python2.5 初始化后会删除 sys.setdefaultencoding 这个方法，我们需要重新载入   
        sys.setdefaultencoding('utf-8')
    global user_path
    if len(sys.argv) > 1:
        user_path = sys.argv[1]
    Logger.init(user_path+'log/')
    if not ConfigManager.loadConfig(user_path):
        sys.exit()

'''
预登录后初始化游戏
@param reconnect: 是否重连
'''
def initGame(reconnect):
    #登录
    print u'开始登录'
    if not LoginManager.login(reconnect):
        print u'登录失败'
        global running
        running = False
        return
    else:
        print u'登录成功'
    #开启心跳
    HeartBeat.start()
    #开启武将管理
    GeneralManager.start()
    #开启资源管理
    ResourceManager.start()
    #开启主城管理
    MaincityManager.start()
    #开启战斗管理
    WarManager.start()
    
'''
刷新等行为导致的退出游戏
'''
def exitGame():
    #暂停心跳
    HeartBeat.pause()
    #暂停武将管理
    GeneralManager.pause()
    #清理武将数据
    GeneralData.clear()
    #暂停资源管理
    ResourceManager.pause()
    #清理资源数据
    ResourceData.clear()
    #暂停主城管理
    MaincityManager.pause()
    #暂停战斗管理
    WarManager.pause()
    #清理战斗数据
    WarData.clear()

def gameCallback():
    PushCommand.init()
    PushCommand.setCallback(PushCommand.PUSH_PLAYER, Role.roleInfoUpdate)
    PushCommand.setCallback(PushCommand.PUSH_GENERAL, General.generalInfoUpdate)
    PushCommand.setCallback(PushCommand.PUSH_WORLD, World.cityInfoUpdate)
    PushCommand.setCallback(PushCommand.PUSH_RESOURCE, Role.resourceUpdate)
    try:
        initGame(False)
        while running:
            #是否处于非连接状态
            if SocketService.gameSocketService.isNotConnected():
                break
            #是否需要重连
            if SocketService.gameSocketService.isReconnected():
                #如果不允许重连
                if not GameConfig.reconnect_enabled:
                    break
                else:
                    exitGame()
                time.sleep(1)
                initGame(True)
            SocketService.gameSocketService.receive()
    except:
        Logger.logException()
    finally:
        ThreadManager.killAllBasicThread()

def userHelp(command):
    params = command.split(' ')
    #获取线程状态
    if command == 'state':
        ThreadManager.state()
    #重新加载配置
    elif command == 'load config':
        ConfigManager.loadConfig(user_path)
    #获取变量值
    elif command.startswith('getvar'):
        print eval(params[1])
    #设置变量值
    elif command.startswith('setvar'):
        pass
    #输出详细信息
    elif command == 'detail':
        pass
    #执行python命令
    elif params[0] == 'exec':
        exec(command[len('exec'):].lstrip(), globals())
    #帮助
    elif command == 'help':
        pass

user_path = ""
running = True
initContext()
gameThread = threading.Thread(name='gameThread', target=gameCallback)
ThreadManager.addThread(gameThread)
gameThread.start()

while True:
    try:
        command = sys.stdin.readline().rstrip()
        userHelp(command)
    except:
        print traceback.format_exc()